using System;
using System.IO;
using System.Data;
using System.Net;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class Download : MissionPlugin
    {       
        [Package(Direction.Input, "Defines all files you like to download.")]
        enum DownloadFiles
        {
            [Column(typeof(string), "The file you like to download to your desktop machine.")]
            FileURLPath
        }

        [Package(Direction.Input, "Defines all the download settings.")]
        enum DownloadSettings
        {
            [Column(typeof(string), "The directory where you like to download your files.",
               Validation = "ispath")]
            DownloadFolder
        }

        [Plugin(PluginDevStatus.Production, "Downloads the given files from the web.")]
        public Download()
        {
        }

        public override void Initialize()
        {
            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }

        protected override void Work()
        {
            DataTableReader downloadSettings = this.GetDataReader(typeof(DownloadSettings));
            while (downloadSettings.Read())
            {
                this.AddNewLoggingMessage(typeof(DownloadSettings), String.Format("create folder if not exist: '{0}'", downloadSettings[DownloadSettings.DownloadFolder.ToString()].ToString()));

                // Create the subfolder if not existing
                if (false == Directory.Exists(downloadSettings[DownloadSettings.DownloadFolder.ToString()].ToString()))
                {
                    System.IO.Directory.CreateDirectory(downloadSettings[DownloadSettings.DownloadFolder.ToString()].ToString());                    
                }

                DataTableReader downloadFiles = this.GetDataReader(typeof(DownloadFiles));
                while (downloadFiles.Read())
                {
                    Uri downloadPath = new Uri(downloadFiles[DownloadFiles.FileURLPath.ToString()].ToString());

                    this.AddNewLoggingMessage(typeof(DownloadFiles), String.Format("download from: '{0}'", downloadPath.AbsoluteUri));

                    System.Net.WebClient client = new WebClient();
                    client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
                    client.DownloadFile(downloadPath.AbsoluteUri, downloadSettings[DownloadSettings.DownloadFolder.ToString()].ToString() + "\\" + downloadPath.Segments[downloadPath.Segments.Length-1]);
                }
            }
        }  
    }
}
